package org.neframework.webtest.util.data;

import java.io.File;
import java.io.FilenameFilter;

import org.neframework.webtest.util.config.Config;

public class DbTools {

	// 备份数据库
	public static File backup() {
		String sqlFile = Config.getConfig().DATA_PATH + File.separator + "db" + File.separator + System.currentTimeMillis() + ".sql";
		try {
			File f = new File(sqlFile);
			if (!f.getParentFile().exists()) {
				f.getParentFile().mkdirs();
			}

			String cmd = "@mysqldump @database -h @localhost -u@uname -p@pwd --default-character-set=utf8 --result-file=@sqlFile";

//			cmd = cmd.replace("@mysqldump", Config.getConfig().DB_DUMP);
//			cmd = cmd.replace("@localhost", Config.getConfig().DB_IP);
//			cmd = cmd.replace("@database", Config.getConfig().DB_NAME);
//			cmd = cmd.replace("@uname", Config.getConfig().DB_UNAME);
//			cmd = cmd.replace("@pwd", Config.getConfig().DB_PWD);
			cmd = cmd.replace("@sqlFile", sqlFile);

			System.err.println(cmd);

			// 调用 调用mysql的安装目录的命令
			Process child = Runtime.getRuntime().exec(cmd);

			if (child.waitFor() == 0) {// 0 表示线程正常终止。
			}

			if (f.length() == 0) {
				return null;
			}
			return f;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}// #backup

	// 还原数据库
	public static boolean restore() {
		File dbFolder = new File(Config.getConfig().DATA_PATH + File.separator + "db");
		if (!dbFolder.exists()) {
			dbFolder.mkdirs();
		}

		String[] sqlFilenames = dbFolder.list(new FilenameFilter() {

			@Override
			public boolean accept(File dir, String name) {
				// TODO Auto-generated method stub
				return name.endsWith(".sql");
			}
		});
		if (sqlFilenames == null || sqlFilenames.length == 0) {
			return true;
		}
		// 选择最后的文件
		long l = 0;
		for (String fname : sqlFilenames) {
			long f = new Long(fname.substring(0, fname.indexOf(".")));
			l = f > l ? f : l;
		}

		File sqlFile = new File(dbFolder, l + ".sql");

		String cmd = "cmd /c @mysql  -h @localhost -u@uname -p@pwd @database<@sqlFile";

//		cmd = cmd.replace("@mysql", Config.getConfig().DB_RESTORE);
//		cmd = cmd.replace("@localhost", Config.getConfig().DB_IP);
//		cmd = cmd.replace("@database", Config.getConfig().DB_NAME);
//		cmd = cmd.replace("@uname", Config.getConfig().DB_UNAME);
//		cmd = cmd.replace("@pwd", Config.getConfig().DB_PWD);
		cmd = cmd.replace("@sqlFile", sqlFile.getAbsolutePath());

		System.err.println(cmd);

		// 调用 调用mysql的安装目录的命令
		try {
			Process child = Runtime.getRuntime().exec(cmd);
			if (child.waitFor() == 0) {// 0 表示线程正常终止。
			}

			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}

	}

	public static void main(String[] args) {
		String s = "1433490461778.sql";
		System.err.println(s.substring(0, s.indexOf(".")));
	}
}
